import axios from 'axios'
import qs from 'querystring'
import { message } from 'antd'
import NProgress from 'nprogress'//进度条库
import store from '../redux/store'
import { createDeleteUserInfoAction } from '../redux/actions/login_action'
import 'nprogress/nprogress.css'

const instance = axios.create({
  timeout: 4000,
});

//请求拦截器
instance.interceptors.request.use(config => {
  //进度条开始
  NProgress.start()
  // console.log(config);
  const { method, data } = config;
  //若是post请求
  if (method.toLowerCase() === 'post') {
    //若是传递过来的参数是对象
    if (data instanceof Object) {
      config.data = qs.stringify(data)
    }
  }
  return config;
})

//响应拦截器
instance.interceptors.response.use(response => {
  //进度条结束
  NProgress.done()
  return response.data;
}, error => {
  NProgress.done()
  if (error.response.status === 401) {
    message.error('身份校验失败，请重新登录', 1)
    store.dispatch(createDeleteUserInfoAction())
  } else {
    //使用antd组件来提示错误信息
    message.error(error.message, 1)
  }

  return new Promise(() => { })//中断传递
})

export default instance;